import { NextRequest, NextResponse } from "next/server";
import axios from "axios";
import { getCurrentUserId } from "@/lib/auth";

export async function POST(req: NextRequest) {
  try {
    const userId = getCurrentUserId();

    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { modelType, type, apiUrl, apiKey, model } = body;

    if (!apiUrl || !apiKey || !model) {
      return NextResponse.json(
        { success: false, error: "缺少必要的API参数" },
        { status: 400 }
      );
    }

    // 测试连接
    try {
      if (modelType === "chat") {
        await testChatModelConnection(type, apiUrl, apiKey, model);
      } else if (modelType === "embedding") {
        await testEmbeddingModelConnection(type, apiUrl, apiKey, model);
      } else {
        throw new Error("未知的模型类型");
      }

      return NextResponse.json({ success: true });
    } catch (error) {
      console.error("模型连接测试失败:", error);
      let errorMessage = "连接失败";

      if (axios.isAxiosError(error)) {
        errorMessage = error.response?.data?.error?.message || error.message;
      } else if (error instanceof Error) {
        errorMessage = error.message;
      }

      return NextResponse.json(
        { success: false, error: errorMessage },
        { status: 400 }
      );
    }
  } catch (error) {
    console.error("处理连接测试请求失败:", error);
    return NextResponse.json(
      { success: false, error: "处理请求失败" },
      { status: 500 }
    );
  }
}

/**
 * 测试聊天模型连接
 */
async function testChatModelConnection(
  type: string,
  apiUrl: string,
  apiKey: string,
  model: string
) {
  // 请求数据
  const requestData = {
    model,
    messages: [
      {
        role: "user",
        content: "Hello, this is a test message. Please respond with 'Connection successful'.",
      },
    ],
    max_tokens: 20,
  };

  // 请求头
  const headers = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${apiKey}`,
  };

  // 发送请求
  const response = await axios.post(apiUrl, requestData, { headers });

  // 验证响应
  if (!response.data) {
    throw new Error("模型未返回有效响应");
  }

  return true;
}

/**
 * 测试嵌入模型连接
 */
async function testEmbeddingModelConnection(
  type: string,
  apiUrl: string,
  apiKey: string,
  model: string
) {
  // 请求数据
  const requestData = type === "openai"
    ? {
        model,
        input: "This is a test text for embedding.",
      }
    : {
        model,
        text: "This is a test text for embedding.",
      };

  // 请求头
  const headers = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${apiKey}`,
  };

  // 发送请求
  const response = await axios.post(apiUrl, requestData, { headers });

  // 验证响应
  if (!response.data) {
    throw new Error("模型未返回有效响应");
  }

  return true;
} 